package com.galaxy.maven.tools.autoconfig;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

    public static String readFile(String filePath) {
        String output = "";
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            FileReader fr = null;
            BufferedReader input = null;
            try {
                fr = new FileReader(file);
                input = new BufferedReader(fr);
                StringBuffer buffer = new StringBuffer();
                String text;
                while ((text = input.readLine()) != null) {
                    buffer.append(text + "\n");
                }
                output = buffer.toString();
            } catch (IOException ioException) {
                throw new RuntimeException("File Error!");
            } finally {
                try {
                    fr.close();
                    input.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            throw new RuntimeException("File does not exist!");
        }
        return output;
    }

    public static void writeFile(String destStr, String target) {
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            File file = new File(target);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdir();
            }
            fw = new FileWriter(file, true);
            pw = new PrintWriter(fw);
            pw.println(destStr);
            
            pw.close();
            fw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void deleteFile(String target) {
        File file = new File(target);
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            }
        }
    }

}
